package com.qigao.mall.web.controller.app.user;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.qigao.mall.api.ShopInfoService;
import com.qigao.mall.api.ShopRecentService;
import com.qigao.mall.api.UserService;
import com.qigao.mall.commons.dto.*;
import com.qigao.mall.commons.enums.IdTypeEnum;
import com.qigao.mall.commons.enums.Result;
import com.qigao.mall.commons.enums.ResultCode;
import com.qigao.mall.commons.enums.UserSourceEnum;
import com.qigao.mall.commons.exceptions.BusinessException;
import com.qigao.mall.commons.po.UserInfo;
import com.qigao.mall.commons.utils.IDUtils;
import com.qigao.mall.commons.utils.MD5Util;
import com.qigao.mall.web.config.QiGaoProperties;
import com.qigao.mall.web.controller.AbstractUserController;
import com.qigao.mall.web.utils.RequestUtils;
import com.qigao.mall.web.utils.ValidatorUtil;
import com.qigao.mall.web.vo.api.UserCondVo;
import com.qigao.mall.web.vo.api.UserCreateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author luiz
 * @Title:com.qigao.mall.web.controller.app
 * @ProjectName three-mall
 * @Description: App用户相关API
 * @date 2019-10-25  16:56
 */
@RestController
@RequestMapping("/app/user")
@Api(tags = "App用户相关API",value = "App用户相关API")
public class AppUserController extends AbstractUserController {
    private static Logger logger= LoggerFactory.getLogger(AppUserController.class);

    @Resource
    UserService userService;
    @Resource
    private ShopInfoService shopInfoService;
    @Resource
    ShopRecentService shopRecentService;
    @Resource
    private QiGaoProperties qiGaoProperties;

    /**
     * 扫码进入店铺
     * @param shopNo 店铺号
     * @param request
     * @return
     */
    @GetMapping("/enterShop/{shopNo}")
    @ResponseBody
    @ApiOperation(value = "扫码进入店铺", notes = "扫码进入店铺")
    public Result enterShop(@PathVariable("shopNo")String shopNo, HttpServletRequest request) {
        UserInfo userInfo = RequestUtils.getCurrentUser(request);
        if (userInfo == null) {
            logger.info("用户未登录,不记录浏览信息..." );
            return Result.newSuccess();
        }
         shopRecentService.saveShopRecent(shopNo,userInfo);
        return Result.newSuccess();
    }

    /**
     * 获取最近浏览的店铺
     * @param request
     * @return
     */
    @GetMapping("/getRecentShop")
    @ResponseBody
    @ApiOperation(value = "获取最近店铺列表", notes = "获取最近店铺列表")
    public Result<List<ShopRecentDto>> getCurrentShop(@RequestParam("shopNo")String shopNo,HttpServletRequest request) {
        UserInfo userInfo = RequestUtils.getCurrentUser(request);
        List<ShopRecentDto> shopRecentDtos=buildDefault(userInfo);
        if(StringUtils.isNotEmpty(shopNo)&&!shopNo.equals(qiGaoProperties.getShopNo())){
            ShopInfoDto shopInfoDto=shopInfoService.findByShopNo(shopNo);
            if(shopInfoDto!=null){
                shopRecentDtos=buildByShop(userInfo,shopInfoDto);
            }
        }else{
            if(userInfo!=null){
                List<ShopRecentDto> shopRecentDtoList=shopRecentService.findByUserNo(userInfo.getUserNo());
                if(shopRecentDtoList!=null&&shopRecentDtoList.size()>=1){
                    shopRecentDtos=shopRecentDtoList;
                }
            }
        }
        return Result.newSuccess(shopRecentDtos);
    }

    private  List<ShopRecentDto> buildDefault(UserInfo userInfo) {
        List<ShopRecentDto> shopRecentDtos=new ArrayList<>();
        ShopRecentDto  shopRecentDto=new ShopRecentDto();
        shopRecentDto.setShopNo(qiGaoProperties.getShopNo());
        shopRecentDto.setShopName(qiGaoProperties.getShopName());
        if(userInfo!=null){
            shopRecentDto.setUserNo(userInfo.getUserNo());
            shopRecentDto.setUserName(userInfo.getUserName());
        }
        shopRecentDtos.add(shopRecentDto);
        return shopRecentDtos;
    }

    private  List<ShopRecentDto> buildByShop(UserInfo userInfo,ShopInfoDto shopInfoDto) {
        List<ShopRecentDto> shopRecentDtos=new ArrayList<>();
        ShopRecentDto  shopRecentDto=new ShopRecentDto();
        shopRecentDto.setShopNo(shopInfoDto.getShopNo());
        shopRecentDto.setShopName(shopInfoDto.getShopName());
        if(userInfo!=null){
            shopRecentDto.setUserNo(userInfo.getUserNo());
            shopRecentDto.setUserName(userInfo.getUserName());
        }
        shopRecentDtos.add(shopRecentDto);
        return shopRecentDtos;
    }

    /**
     * 添加客户
     * @param userCreateVo
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/createCustomer")
    @ApiOperation(value = "添加客户", notes = "添加客户")
    public Result createCustomer(@RequestBody UserCreateVo userCreateVo, HttpServletRequest request) {
        //校验用户实体字段，
        ValidatorUtil.validateEntity(userCreateVo);
        try {
            UserCreateDto userCreateDto = new UserCreateDto();
            BeanUtils.copyProperties(userCreateVo, userCreateDto);
            userCreateDto.setLoginPass("123456");
            userCreateDto.setNickName(userCreateVo.getUserName());
            //默认等于手机号
            userCreateDto.setUserNo(userCreateVo.getPhoneNum());
            userCreateDto.setTel(userCreateVo.getPhoneNum());
            userCreateDto.setUserSource(UserSourceEnum.CUSTOMER.getCode());
            userCreateDto.setOperNo(RequestUtils.getCurrentUserNo(request));
            return userService.createUser(userCreateDto);
        } catch (BusinessException be) {
            logger.warn("添加客户业务异常!{}", be);
            return Result.newError(be.getCode(), be.getMsg());
        } catch (Exception e) {
            logger.error("添加客户异常!{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //1.按照用户获取客户列表
    @GetMapping("findCustomerList")
    @ApiOperation(value = "按照用户获取客户列表", notes = "按照用户获取客户列表")
    public Result findCustomerList(UserCondVo userCondVo,HttpServletRequest request){
        try{
            String userNo=RequestUtils.getCurrentUserNo(request);
            UserCondDto userCondDto = buildParam(userCondVo);
            userCondDto.setCreateNo(userNo);
            Page<UserResultDto> userPage = userService.findUserPage(userCondDto);
            PageInfo pageInfo = new PageInfo(userPage);
            return Result.newSuccess(pageInfo);
        }catch (Exception e){
            logger.error("获取客户列表发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    private UserCondDto buildParam(UserCondVo userCondVo) {
        UserCondDto userCondDto = new UserCondDto();
        BeanUtils.copyProperties(userCondVo, userCondDto);
        return userCondDto;
    }



}
